package net.htjs.juc.chapter06.atomicreference;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

public class DecimalAccountCas implements DecimalAccount{

    private AtomicReference<BigDecimal> balance;

    public DecimalAccountCas(AtomicReference<BigDecimal> balance) {
        this.balance = balance;
    }

    @Override
    public BigDecimal getBalance() {
        return this.balance.get();
    }

    @Override
    public void withdraw(BigDecimal amount) {
        this.balance.updateAndGet(v -> v.subtract(amount));
        /*while(true) {
            BigDecimal prev = balance.get();
            BigDecimal next = prev.subtract(amount);
            if(balance.compareAndSet(prev, next)) {
                break;
            }
        }*/
    }

    public static void main(String[] args) {
        DecimalAccountCas account = new DecimalAccountCas(new AtomicReference<>(new BigDecimal(10000)));
        DecimalAccount.demo( account);
    }
}
